// pages/detailed/detailed.js
const {
    fetchdetailedMovie,
    fetchWantSeeMovie
} = require('../../api/index.js')

const {
    fetchGetOpenid,
    fetchPayOrder
} = require('../../api/user.js')

const {
    wxApiPromisify
} = require('../../utils/util.js')

let wxProLogin = wxApiPromisify(wx.login)

Page({

    /**
     * 页面的初始数据
     */
    data: {
        id: '',
        movie: {},
        wantsee: false
        // Dynamic_class:true

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: async function (options) {
        let id = options.id
        this.setData({
            id
        })
        //获取电影详情的所有数据显示
        // console.log(id);
        let movie = await fetchdetailedMovie(id)
        // console.log(movie);
        //替换掉wh
        movie.data.movie.img = movie.data.movie.img.replace(/\/w\.h/, '')
        movie.data.movie.photos = movie.data.movie.photos.map(item => {
            item = item.replace(/\/w\.h/, '')
            return item
        })
        this.setData({
            movie
        })
        console.log(this.data.movie.data.movie.photos);
    },
    //想看的电影
    async wantSee() {
        let {
            message,
            errcode
        } = await fetchWantSeeMovie(this.data.id)
        if (errcode == 200) {
            wx.showToast({
                title: '加入成功'
            })
            this.setData({
                isSee: true
            })
        }
    },
    //下订单
    async buyMovie() {
        // 先获取openid
        let openid = wx.getStorageSync('openid')
        if (!openid) {
            // 直接进入到要授权的页面
            wx.navigateTo({
                url: '/pages/user/user',
            })
            return;
        }
        // 在调用支付接口 传递 openid,movieid,获取预支付参数
        try {
            let prepayData = await fetchPayOrder(this.data.id, openid);
            console.log(prepayData);
            if (prepayData.errcode !== 200) {
                wx.showToast({
                    title: prepayData.message,
                })
                return;
            }
            let {
                nonce_str,
                mypackage,
                sign_type,
                paySign,
                timeStamp
            } = prepayData.result.xml;
            // 调用wxwx.requestPayment拉起微信支付
            wx.requestPayment({
                nonceStr: nonce_str,
                package: mypackage,
                signType: sign_type,
                paySign: paySign,
                timeStamp: timeStamp,
                complete() {
                    wx.redirectTo({
                        url: '/pages/order/order',
                    })
                },
            })
        } catch (err) {
            console.log('error message:', err.message)
        }

    },
    // showAllDesc(){
    //     this.setData({
    //         Dynamic_class:!this.data.Dynamic_class
    //     })
    // }
    //加入想看电影
    // wantSee() {
    //     wx.showToast({
    //         title: '加入成功'
    //     })
    // }
})